package cn.xshi.oauth.web;
import cn.xshi.common.entity.index.*;
import cn.xshi.oauth.form.OauthSysModulesForm;
import cn.xshi.oauth.model.OauthAccount;
import cn.xshi.oauth.model.OauthResources;
import cn.xshi.oauth.model.OauthSysModules;
import cn.xshi.oauth.service.OauthAccountService;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import cn.xshi.common.annotation.Auth;
import cn.xshi.common.base.BaseAction;
import cn.xshi.common.base.BaseHttpSessionEntity;
import cn.xshi.common.base.BaseResult;
import cn.xshi.common.entity.LoginEntity;
import cn.xshi.common.entity.OauthAccountEntity;
import cn.xshi.common.entity.OauthAdminSysEntity;
import cn.xshi.common.entity.UpdatePasswordEntity;
import cn.xshi.common.util.MD5;
import cn.xshi.common.util.ExceptionUtil;
import cn.xshi.common.util.JsonUtil;
import cn.xshi.common.util.SortUtil;
import cn.xshi.common.util.StringUtil;
import cn.xshi.oauth.service.OauthSysModeService;
import cn.xshi.oauth.util.OauthUtil;
import cn.xshi.oauth.service.OauthResourcesService;
import cn.xshi.oauth.service.OauthSysModulesService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
/**
 * @Desc 授权中心主页API
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@RestController
@Api(value = "授权中心主页API",tags = "授权中心主页API",description = "授权中心主页API")
public class OauthIndexController extends BaseAction {

    @Resource
    private OauthResourcesService oauthResourcesService;

    @Resource
    private OauthSysModulesService oauthSysModulesService;

    @Resource
    private OauthUtil oauthUtil;

    @Resource
    private OauthAccountService oauthAccountService;

    @Resource
    private OauthSysModeService oauthSysModeService;

    /**
     * 初始化主页面
     * @param request
     * @return
     */
    @ApiOperation(value="初始化主页面", notes="初始化主页面")
    @PostMapping(value="/init")
    @Auth(value = "/init",authenticationType = Auth.AuthorizationType.REQUIRED_LOGIN_NOT_AUTH)
    @Deprecated
    public BaseResult init(HttpServletRequest request){
        String info = oauthUtil.getTokenInfo(request);
        BaseHttpSessionEntity baseHttpSessionEntity = JsonUtil.fromAliFastJson(info, BaseHttpSessionEntity.class);
        String oauthAdminSysEntity = baseHttpSessionEntity.getOauthAdminSysEntities();
        List<OauthAdminSysEntity> oauthAdminSysEntities = JsonUtil.toFList(oauthAdminSysEntity, OauthAdminSysEntity.class);

        List<OauthResources> oauthResourcesList = null;
        List<String> idList = commonSysModulesId(oauthAdminSysEntities);
        Map<String, Object> condition = new HashMap<String, Object>();
        if(null != idList && !idList.isEmpty()){
            //各子系统管理员拥有的资源模块
            condition.put("sysModuleId",idList);
            oauthResourcesList = oauthResourcesService.getOauthResourcesListByCondition(condition);
        }else{
            //各子系统角色
            if(null == baseHttpSessionEntity){
                condition.put("roleId", "-1".split(","));
            }else{
                String roleId = baseHttpSessionEntity.getRoleId();
                if(!StringUtils.isEmpty(roleId)){
                    condition.put("roleId", roleId.split(","));
                }else{
                    condition.put("roleId", "-1".split(","));
                }
            }
            oauthResourcesList = oauthResourcesService.getResourcesListForRole(condition);
        }

        InitAdminPage initAdminPage = new InitAdminPage();

        SortUtil<OauthResources> sortUtil = new SortUtil<OauthResources>();

        sortUtil.Sort(oauthResourcesList, "sort", "asc");

        String json = JsonUtil.toFastJson(oauthResourcesList);

        List<ResourceEntity> resourceEntities = JsonUtil.toFList(json, ResourceEntity.class);

        Map<String,List<ResourceEntity>> map = commonResourceEntities(resourceEntities);//转换资源集合

        if(!CollectionUtils.isEmpty(map)){
            Iterator<Map.Entry<String, List<ResourceEntity>>> entries = map.entrySet().iterator();
            while (entries.hasNext()) {
                Map.Entry<String, List<ResourceEntity>> entry = entries.next();
                IndexTree tree = new IndexTree(entry.getValue());
                MenuEntity menuEntity = new MenuEntity();
                menuEntity.setSysModeId(entry.getKey());
                menuEntity.setSysModeIcon(entry.getValue().get(0).getSysModeIcon());
                menuEntity.setSysName(entry.getValue().get(0).getSysName());
                menuEntity.setSysModeUrl(entry.getValue().get(0).getSysModeUrl());
                menuEntity.setMenuList(tree.buildTree(false));
                menuEntity.setSort(entry.getValue().get(0).getSort());
                initAdminPage.getMenuEntity().add(menuEntity);
            }
        }

        sortUtil.Sort(initAdminPage.getMenuEntity(), "sort", "ASC");
        AdminTree adminTree = new AdminTree(resourceEntities);
        initAdminPage.setAdminMenuList(adminTree.buildTree());

        initAdminPage.setBasePath(request.getContextPath());

        initAdminPage.setOauthAccountEntity(getCurrentAccountInfo());//当前用户
        return outDataStr(initAdminPage);
    }

    /**
     * 初始化主页面
     * @param request
     * @return
     */
    @ApiOperation(value="初始化主页面V1", notes="初始化主页面V1（vue版本）")
    @GetMapping(value="/init/v1")
    @Auth(value = "/init/v1",authenticationType = Auth.AuthorizationType.REQUIRED_LOGIN_NOT_AUTH)
    public BaseResult initV1(HttpServletRequest request){

        String info = oauthUtil.getTokenInfo(request);

        BaseHttpSessionEntity baseHttpSessionEntity = JsonUtil.fromAliFastJson(info, BaseHttpSessionEntity.class);

        String oauthAdminSysEntity = baseHttpSessionEntity.getOauthAdminSysEntities();

        List<OauthAdminSysEntity> oauthAdminSysEntities = JsonUtil.toFList(oauthAdminSysEntity, OauthAdminSysEntity.class);

        List<OauthResources> oauthResourcesList = null;

        List<String> idList = commonSysModulesId(oauthAdminSysEntities);

        Map<String, Object> condition = new HashMap<String, Object>();

        if(null != idList && !idList.isEmpty()){
            //各子系统管理员拥有的资源模块
            condition.put("sysModuleId",idList);
            oauthResourcesList = oauthResourcesService.getOauthResourcesListByCondition(condition);
        }else{
            //各子系统角色
            if(null == baseHttpSessionEntity){
                condition.put("roleId", "-1".split(","));
            }else{
                String roleId = baseHttpSessionEntity.getRoleId();
                if(!StringUtils.isEmpty(roleId)){
                    condition.put("roleId", roleId.split(","));
                }else{
                    condition.put("roleId", "-1".split(","));
                }
            }
            oauthResourcesList = oauthResourcesService.getResourcesListForRole(condition);
        }

        InitAdminPage initAdminPage = new InitAdminPage();

        SortUtil<OauthResources> sortUtil = new SortUtil<OauthResources>();

        sortUtil.Sort(oauthResourcesList, "sort", "asc");

        String json = JsonUtil.toFastJson(oauthResourcesList);

        List<ResourceEntity> resourceEntities = JsonUtil.toFList(json, ResourceEntity.class);

        Map<String,List<ResourceEntity>> map = commonResourceEntities(resourceEntities);//转换资源集合

        if(!CollectionUtils.isEmpty(map)){
            Iterator<Map.Entry<String, List<ResourceEntity>>> entries = map.entrySet().iterator();
            while (entries.hasNext()) {
                Map.Entry<String, List<ResourceEntity>> entry = entries.next();
//                IndexTreeV1 tree = new IndexTreeV1(entry.getValue());
                MenuEntity menuEntity = new MenuEntity();
                menuEntity.setSysModeId(entry.getKey());
                menuEntity.setSysModeIcon(entry.getValue().get(0).getSysModeIcon());
                menuEntity.setSysName(entry.getValue().get(0).getSysName());
                menuEntity.setSysModeUrl(entry.getValue().get(0).getSysModeUrl());
//                menuEntity.setMenuList(tree.buildTree(false));
                menuEntity.setMenuList(JSONObject.toJSONString(entry.getValue(), SerializerFeature.WriteMapNullValue));
                menuEntity.setSort(entry.getValue().get(0).getModeSort());
                initAdminPage.getMenuEntity().add(menuEntity);
            }
        }

        sortUtil.Sort(initAdminPage.getMenuEntity(), "sort", "ASC");

        AdminTreeV1 adminTreeV1 = new AdminTreeV1(resourceEntities);

        initAdminPage.setAdminMenuList(adminTreeV1.buildTree());

        initAdminPage.setBasePath(request.getContextPath());

        initAdminPage.setOauthAccountEntity(getCurrentAccountInfo());//当前用户

        return outDataStr(initAdminPage);
    }

    /**
     *
     * @param resourceEntities
     */
    public Map<String,List<ResourceEntity>> commonResourceEntities(List<ResourceEntity> resourceEntities){
        Map<String,List<ResourceEntity>> map = new HashMap<>();
        if(!resourceEntities.isEmpty()){
            for(ResourceEntity resourceEntity : resourceEntities){
                List<ResourceEntity> resourceEntityList = map.get(resourceEntity.getSysModeId());
                if(null == resourceEntityList || resourceEntityList.isEmpty()){
                    resourceEntityList = new ArrayList<>();
                }
                resourceEntityList.add(resourceEntity);
                map.put(resourceEntity.getSysModeId(),resourceEntityList);
            }
        }
        return map;
    }

    /**
     *
     * @param oauthAdminSysEntities
     * @return
     */
    public List<String> commonSysModulesId(List<OauthAdminSysEntity> oauthAdminSysEntities){
        List<String> idList = new ArrayList<>();
        List<String> sysModeIdList = new ArrayList<>();
        if(oauthAdminSysEntities == null || oauthAdminSysEntities.isEmpty() || oauthAdminSysEntities.size() == 0){
            return idList;
        }
        for(OauthAdminSysEntity oauthAdminSysEntity : oauthAdminSysEntities){
            sysModeIdList.add(oauthAdminSysEntity.getSysModeId());
        }
        if(null == sysModeIdList || sysModeIdList.isEmpty() || sysModeIdList.size() == 0){
            return idList;
        }
        OauthSysModulesForm oauthSysModulesForm = new OauthSysModulesForm();
        oauthSysModulesForm.setSysModeId(String.join(",",sysModeIdList));
        List<OauthSysModules> oauthSysModulesList = oauthSysModulesService.getOauthSysModulesListByCondition(oauthSysModulesForm);
        for(OauthSysModules oauthSysModules:oauthSysModulesList){
            idList.add(oauthSysModules.getId());
        }
        return idList;
    }

    /**
     * 解锁
     * @param loginEntity
     * @return
     */
    @ApiOperation(value="解锁", notes="解锁")
    @PostMapping(value="/unlock")
    @Auth(value = "/unlock",authenticationType = Auth.AuthorizationType.REQUIRED_LOGIN_NOT_AUTH)
    public BaseResult unlock(@RequestBody(required=true)LoginEntity loginEntity,HttpServletRequest request){
        String password = loginEntity.getPassword();
        if(StringUtil.isEmpty(password)){
            throw new ExceptionUtil("未能获取到密码！");
        }
        OauthAccountEntity oauthAccountEntity = getCurrentAccountInfo();
        MD5 md5 = new MD5();
        password = md5.getMD5ofStr(password.trim());
        Map<String, Object> condition = new HashMap<String, Object>();
        condition.put("password", password);
        condition.put("account", oauthAccountEntity.getAccount());
        condition.put("sysModeId",oauthSysModeService.getSysModeId(request));
        OauthAccount oauthAccount = oauthAccountService.login(condition);
        if(null != oauthAccount){
            return outAudStr(true,"1");
        }else{
            return outAudStr(true,"2");
        }
    }

    /**
     * 修改密码
     * @param updatePasswordEntity
     * @return
     */
    @PostMapping(value="/updatePwd")
    @ApiOperation(value="修改密码", notes="修改密码")
    @Auth(value = "/updatePwd",authenticationType = Auth.AuthorizationType.REQUIRED_LOGIN_NOT_AUTH)
    public BaseResult updatePwd(@RequestBody(required=true)UpdatePasswordEntity updatePasswordEntity, HttpServletRequest request){
        String newPwd = updatePasswordEntity.getNewPwd();
        String oldPwd = updatePasswordEntity.getOldPwd();
        if(StringUtil.isEmpty(newPwd)){
            throw new ExceptionUtil("未能获取到新密码！");
        }
        if(StringUtil.isEmpty(oldPwd)){
            throw new ExceptionUtil("未能获取到原密码！");
        }
        OauthAccountEntity oauthAccountEntity = getCurrentAccountInfo();
        MD5 md5 = new MD5();
        oldPwd = md5.getMD5ofStr(oldPwd.trim());
        newPwd = md5.getMD5ofStr(newPwd.trim());
        Map<String, Object> condition = new HashMap<String, Object>();
        condition.put("password", oldPwd);
        condition.put("account", oauthAccountEntity.getAccount());
        condition.put("sysModeId",oauthSysModeService.getSysModeId(request));
        OauthAccount oauthAccount = oauthAccountService.login(condition);
        if(null == oauthAccount){
            throw new ExceptionUtil("原密码错误！");
        }
        updatePasswordEntity.setNewPwd(newPwd);
        updatePasswordEntity.setAccountId(oauthAccount.getId());
        int i = oauthAccountService.updatePwd(updatePasswordEntity);
        if(i > 0){
            return BaseResult.success();
        }else{
            return BaseResult.fail();
        }
    }
}
